<script setup lang="ts">
import { ref, onBeforeMount, onMounted,computed,nextTick} from "vue";
import {ElMessage as message } from "element-plus";
import { setTableHeight,setFixedColumnWidth} from "@/common/utils";
import useUserList,{actionKeys} from "./userList";
import useRoleList from '@/views/sysAuth/role/roleList'
import MyTable from "@/components/Table/myTable.vue";
import Add from "./add.vue";
import Update from "./update.vue";

const columns= ref<tableColConfig[]>([
  {
    label: "用户名",
    prop: "userName",
    columnKey: "userName",
    minWidth: 150,
    align: "center",
  },
  {
    label: "拥有的角色",
    prop: "roleNames",
    columnKey: "roleNames",
    minWidth: 150,
    align: "center",
    ellipsis: true,
  },
  {
    label: "昵称",
    prop: "nickName",
    columnKey: "nickName",
    minWidth: 150,
    align: "center",
  },
  {
    label: "操作",
    prop: "operation",
    columnKey: "operation",
    fixed: "right",
    align: "center",
    width: 128,
  },
])
const isSearching = ref(false)
const searchList = ref<RoleItem[]>([])
const tableHeight = ref<number>()
const addModalVisible = ref(false);
const updateModalVisible = ref(false);
const editUser = ref({} as userType);
const addRef = ref<InstanceType<typeof Add>>()
const updateRef = ref<InstanceType<typeof Update>>()
const tableRef = ref<InstanceType<typeof MyTable>>()
const userList = useUserList();
const roleList=useRoleList()
const searchOptions=ref<searchOptionType[]>([
	{type:'input',id:'userName',props:{label:'用户名'}},
	{type:'input',id:'nickName',props:{label:'昵称'}},
	{type:'select',id:'role',props:{label:'角色'},innerComponentProps:{filterable:true,selectOptions:[
					// { label: '商品类型1', value: '1',disabled:false },
	  ],
	}},
])

const tableData = computed(() => {
	if (!tableRef.value) return []
	const pageNum = tableRef.value!.pageNum
	const pageSize = tableRef.value!.pageSize
	return JSON.parse(JSON.stringify(userList.list)).splice((pageNum - 1) * pageSize, pageSize)
})

onBeforeMount(() => {
  userList.getList();
  searchOptions.value.forEach(v=>{
		if(v.id==='role')  
		v.innerComponentProps!.selectOptions=roleList.list.map(v=>({label:v.roleName,value:v.roleName}))
	})
});

onMounted(() => {
  setFixedColumnWidth([actionKeys.update,actionKeys.delete],columns)
});

function sethandleSearchPanelcollapsed(h:number){
	setTableHeight({tableHeightRef:tableHeight,otherSectionHeight:h}) 
}

function search(value:objType){
   //console.log(value)
	 let _searchList=JSON.parse(JSON.stringify(userList.list))
   if(value.userName) _searchList=_searchList.filter((v:userType)=>v.userName===value.userName)
   if(value.nickName) _searchList=_searchList.filter((v:userType)=>v.nickName===value.nickName)
   if(value.role) _searchList=_searchList.filter((v:userType)=>v.roles.includes(value.role))
	 searchList.value=_searchList
	 isSearching.value=true
}

function reset() {
  isSearching.value = false
  userList.getList();
  tableRef.value?.reset()
}
function handleAdd() {
  addModalVisible.value = true;
  nextTick(()=>{addRef.value?.init()})
}
async function handleAddCommit() {
  const isSuccess=await addRef.value?.formCommit()
  if (isSuccess) {
    addModalVisible.value = false;
    message.success("新增成功");
  }
}
function handleUpdate(row: userType) {
  editUser.value = row;
  updateModalVisible.value = true;
  nextTick(()=>{updateRef.value?.init()})
}
async function handleUpdateCommit() {
    const isSuccess=await updateRef.value?.formCommit()
  if (isSuccess) {
    updateModalVisible.value = false;
    message.success("更新成功");
  }
}
async function handleDelete(row: userType) {
  const res = await userList.deleteItem(row.id);
  if (res.code) {
    message.success("删除成功");
  }
}
</script>

<template>
  <div class="userManage">
    <search-panel :options="searchOptions"  @collapsed="sethandleSearchPanelcollapsed" @reset="reset" @search="search" />
    <div class="tableTool">
      <el-button type="primary" style="margin-right: 5px" @click="handleAdd"
      v-if="$hasAuth([actionKeys.add])">新增用户</el-button
      >
    </div>
    <my-table
      :data="isSearching ? searchList : tableData"
      :columns="columns"
      size="small"
      style="width: 100%"
      class="myTable"
      rowKey="name"
      :height="tableHeight+'px'"
      :maxHeight="tableHeight"
      :pagination="{
        pageSizes: [10, 20, 30, 40, 50],
        small: true,
        background: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total:isSearching ? searchList.length : userList.list.length,
      }"
      ref="tableRef"
    >
        <template #operation="{row}">
          <el-button type="primary" size="small" @click="handleUpdate(row)" v-if="$hasAuth([actionKeys.update])">修改</el-button>
						<el-popconfirm title="确定要删除吗?" confirm-button-text="确定" cancel-button-text="取消" @confirm="handleDelete(row)" v-if="$hasAuth([actionKeys.delete])">
							<template #reference><el-button type="danger" size="small" >删除</el-button></template>
						</el-popconfirm>
        </template>
    </my-table>

    <el-dialog v-model="addModalVisible" title="新增用户" width="80%" :modal="false" draggable :close-on-click-modal="false" align-center>
			<Add  ref="addRef" />
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="addModalVisible = false">取消</el-button>
					<el-button type="primary" @click="handleAddCommit">确定</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog v-model="updateModalVisible" title="更新用户" width="80%" :modal="false" draggable :close-on-click-modal="false" align-center>
			<Update :editUser="editUser"  ref="updateRef" />
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="updateModalVisible = false">取消</el-button>
					<el-button type="primary" @click="handleUpdateCommit">确定</el-button>
				</div>
			</template>
		</el-dialog>
  </div>
</template>

<style scoped lang="scss">
.userManage {
  .tableTool {
    padding: 10px 0;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  :deep(.el-table thead .el-table__cell) {
		text-align: center ;
		// background-color: rgb(232, 246, 241) !important;
}
}
</style>
